/**
 * Created by chenweicheng on 8/3/2017.
 */
/**
 * Created by chenweicheng on 1/3/2017.
 */
/**
 * Created by Administrator on 2016/12/20 0020.
 */

import React, {Component} from 'react';
import {
    AppRegistry, View, Text, ScrollView, Image, StyleSheet, TouchableHighlight, NativeAppEventEmitter,
    Platform,
    PermissionsAndroid,
} from 'react-native';

import BleManager from '../BleManager';

export default class TestProtoManager extends Component {

    constructor(props) {
        super(props);
        this.state = {
            ble: null,
            connectState: 'disconnected',
        };

        this.scanning = false;

    }


    headerType = {
        BabyBathMessage: 1,
        ReadyMessage: 2,
    };

    strAddHeader(str, headerType) {
        console.log("headerType=", headerType);
        switch (headerType) {


            case this.headerType.BabyBathMessage:
                console.log("headerType.BabyBathMessage");
                return "00" + str;

            case this.headerType.ReadyMessage:
                console.log("headerType.ReadyMessage");
                return "01" + str;
            default:
                return str;
        }
    }

    formatStr(str) {
        if (str.length == 1) {
            return "0" + str
        } else {
            return str
        }
    }

    /*
     1.生成java可解析16进制字符串
     2、将1中16进制字符串翻转
     3、protobufjs支持本地proto文件

     */


    componentDidMount() {

        BleManager.start({showAlert: true}).then(() => {
            console.log("start successss:");
            //检查蓝牙开关
            BleManager.checkState();
        }, (error) => {
            console.log("start fail" + error);
        });
        if (Platform.OS === 'android') {
            //发现设备广播
            this.handleDiscoverPeripheral = NativeAppEventEmitter
                .addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral.bind(this));
            //连接设备成功广播
            this.handleConnectedPeripheral = NativeAppEventEmitter
                .addListener('BleManagerConnectPeripheral', this.handleConnectedPeripheral.bind(this));
            //断开连接成功广播
            this.handleDisConnectedPeripheral = NativeAppEventEmitter
                .addListener('BleManagerDisconnectPeripheral', this.handleDisConnectedPeripheral.bind(this));
            //收到数据广播
            this.handleNotification = NativeAppEventEmitter
                .addListener('BleManagerDidUpdateValueForCharacteristic', this.handleNotification.bind(this));
            this.handleBleManagerDidUpdateState = NativeAppEventEmitter
                .addListener('BleManagerDidUpdateState', this.handleBleManagerDidUpdateState.bind(this));
        } else {
            //发现设备广播
            this.handleDiscoverPeripheral = myNativeEvt
                .addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral.bind(this));
            //连接设备成功广播
            this.handleConnectedPeripheral = myNativeEvt
                .addListener('BleManagerConnectPeripheral', this.handleConnectedPeripheral.bind(this));
            //断开连接成功广播
            this.handleDisConnectedPeripheral = myNativeEvt
                .addListener('BleManagerDisconnectPeripheral', this.handleDisConnectedPeripheral.bind(this));
            //收到数据广播
            this.handleNotification = myNativeEvt
                .addListener('BleManagerDidUpdateValueForCharacteristic', this.handleNotification.bind(this));
            this.handleBleManagerDidUpdateState = myNativeEvt
                .addListener('BleManagerDidUpdateState', this.handleBleManagerDidUpdateState.bind(this));
        }

        if (Platform.OS === 'android' && Platform.Version >= 23) {
            PermissionsAndroid.checkPermission(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
                if (result) {
                    console.log("Permission is OK");
                } else {
                    PermissionsAndroid.requestPermission(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
                        if (result) {
                            console.log("User accept");
                        } else {
                            console.log("User refuse");
                        }
                    });
                }
            });
        }
        this.startScan(true)


    }

    static componentWillUnmount() {
        //反注册广播
        NativeAppEventEmitter.removeAllListeners();
    }

    handleConnect(data) {

        BleManager.connect(data['id']).then((map) => {
            this.handleStartNotification(this.state.ble);
        }, (error) => {
            console.log("connect fail");
            console.log(error);

        });
    }

    handleStartNotification(data) {
        BleManager.setNotification(data['id']).then(
            () => {
                console.log('start notification success')
            },
            (error) => {
                console.log('start notification fail', error)
            });
    }

    handleDiscoverPeripheral(data) {
        if (data['name'] == null) {

        } else {
            var name = data['name'];
            var fdStart = name.indexOf("SmartUp");
            if (fdStart == 0) {
                // 表示strCode是以ssss开头；
                clearInterval(this.scanId);
                this.scanning = false;
                this.setState({ble: data});
                this.handleConnect(this.state.ble)
            } else if (fdStart == -1) {
                //  表示strCode不是以ssss开头
                console.log('handleDiscoverPeripheral')

            }
        }
    }

    handleConnectedPeripheral(data) {
        this.setState({connectState: 'connected'});
    }

    handleDisConnectedPeripheral(data) {
        this.setState({connectState: 'disconnected'});
        this.startScan(true);
        // alert('糟糕，断开了')
    }

    handleNotification(data) {

        console.log('handleNotification', data);

    }

    handleBleManagerDidUpdateState(data) {
        if (data['state'] == "on") {
        } else if (data['state'] == "off") {
            this.setState({connectState: 'disconnected'});
            BleManager.enableBluetooth().then(() => {
                console.log('BLE 开关打开成功',);
            }, (result) => {
                console.log('BLE 开关打开失败', result);
            });
        }

    }

    startScan(bool) {
        if (bool) {
            this.scanning = true;
            this.scanId = setInterval(() => this.handleScan(), 5000);
        } else {
            this.scanning = false;
            clearInterval(this.scanId);
            BleManager.stopScan().then(() => {
                console.log('stop scan success')
            }, (error) => {
                console.log('stop scan fail')
            })

        }
    }

    handleScan() {
        BleManager.scan(3, 'SmartUp+')
            .then(() => {
                //  console.log('Scanning.Success..')
            }, (error) => {
                //    console.log('Scanning...fail')
            });
    }

    handleWriteBack(ble, data) {


        BleManager.writeBack(ble['id'], data).then((map) => {
            console.log("handleWriteBack..success");
            console.log(map)
        }, (error) => {
            console.log("handleWriteBack..fail");
            console.log(error)
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <TouchableHighlight style={{padding: 20, backgroundColor: '#ccc'}}
                                    onPress={() =>this.handleWriteBack(this.state.ble,'aac8b0a318593647fd24d6')  }>
                    <Text>handleWriteBack</Text>
                </TouchableHighlight>
            </View>
        );
    }
}
//aac8b0a318593647fd24d6  ///aac8b0a718593647fd2422
var styles = StyleSheet.create({
    container: {
        //   justifyContent: 'center',
        flex: 1,
        flexDirection: 'column',//没有flexDirection这个属性的话，justifyContent不会生效
        justifyContent: 'center',
        padding: 15,
        alignItems: 'center'
    }
});
AppRegistry.registerComponent('TestProtoManager', () => TestProtoManager);